package com.mapull.simple;

/**
 * 二分查找
 * @author mapull
 * @date 2022-06-05
 */
public class Binary {

    public static void main(String[] args) {
        int[] nums = {1,3,4,5,7,9};
        int target = 3;
        int idx = binarySearch(nums, target);
        System.out.println(idx);
    }

    private static int binarySearch(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;
        while(left <= right){
            int mid = (left + right) >>> 1;
            if(arr[mid] > target){
                right = mid - 1;
            }else if(arr[mid] < target){
                left = mid + 1;
            }else{
                return mid;
            }
        }
        return -1;
    }
}
